<?php
namespace App\Logic;

use Common\Model\CollectionModel;

class CollectionLogic extends CollectionModel 
{
	private $expire_time = 90; //过期天数
	
	protected function _initialize()
	{
		parent::_initialize();
	}
	
	public function updateCollection( $data = array() )
	{
		$data = $this->create($data);
		
		if( $data === false )
		{
			return false;
		}
		
		$data['collection_data'] = base64_decode($data['collection_data'],true);
		
		if( $data['collection_data'] === false )
		{
			$this->error = 'data数据格式有误';
			
			return false;
		}
		
		$collection = $this->where(array('collection_key'=>$data['collection_key']))->getItem();
				
		if( empty($collection) === false )
		{
			$time_diff = time() - strtotime($collection['collection_time']);
			
			//判断过期时间 >=90days:更新记录，<90days:不更新记录
			if( $time_diff >= ($this->expire_time)*86400 )
			{
				$data['collection_id'] = $collection['collection_id'];
			}
			else 
			{
				return true;
			}
		}
		
		$data['collection_time'] = date("Y-m-d H:i:s",time());
		
		if( $this->updateRecord($data) === false )
		{
			return false;
		}
		
		return true;
	}
	
	public function checkRequire($required = array(),$query = array())
	{
		$diff = array_diff($required,array_keys($query));
		
		if( empty($diff) === false )
		{
			foreach ($diff as $row)
			{
				$this->error .= $row . '不能为空,';
			}
				
			$this->error = trim($this->error,',');
				
			return false;
		}
		return true;
	}
	
	public function getSecretKey() 
	{
		return '72969e04baa8b6e43fae34e1969d56a6';
	}
	
	public function checkSign($data) 
	{
		$clientSign = $data['sign'];
		
		$sign = $this->getSign($data);
		
		return $clientSign === $sign;
	}
	
	public function getSign($data)
	{
		unset($data['sign']);
		
		$sk = $this->getSecretKey();
		
		ksort($data);
		$query = '';
		
		foreach ($data as $key => $item)
		{
			$query .= "&{$key}={$item}";
		}
	
		$query = trim($query,'&');
		$query .= $sk;
		
		return md5($query);
	}
}
